﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using TranTekBE.NhaThuoc;

namespace TranTekBE.Kho
{
    public partial class ChuyenHang : PageRequireLogin
    {
        public List<ModelUser> listUser;
        public Database database = new Database(TinyLib.GetConfigKey("ConnectionString2"));
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                LoadDDlCH();
                dateFrom.Text = dateTo.Text = DateTime.Now.ToString("MM/dd/yyyy");
                ViewState["SortExpression"] = "Ngay DESC";
                LoadGridview();
                GridViewRow header = GridView1.HeaderRow;
            }
            ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "LoadDatePiker", "LoadDatePiker();", true);
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
        }
        void LoadDDlCH()
        {
            GridView1.DataBind();
            string sql = @"SELECT [C007001] CHName FROM [192.168.1.98\CAMSOFT].[POSPRO_20130107].[dbo].[T0070] where [C007001] not in ('RACHMIEU','PMT')";
            var ds = database.ExecuteQuery(sql);
            if (ds.Tables.Count > 0)
            {

                // GridViewRow header = GridView1.HeaderRow;
                //  if (header != null)
                {

                    //    DropDownList ddlCuaHangChuyen = GridView1.HeaderRow.Cells[0].FindControl("ddlCuaHangChuyen") as DropDownList;
                    //    DropDownList ddlCuaHangNhan = GridView1.HeaderRow.FindControl("ddlCuaHangNhan") as DropDownList;

                    ThuVien.FunctionsUtils.BindDataForControlList(ddlCuaHangChuyen, ds, "CHName", "CHName", "", "--Tất cả--");
                    ThuVien.FunctionsUtils.BindDataForControlList(ddlCuaHangNhan, ds, "CHName", "CHName", "", "--Tất cả--");

                }
            }
        }
        void LoadGridview()
        {
            string str = @"SELECT l.*,r.NgayXuLy,r.CuaHangChuyen,r.CuaHangNhan,r.UserChuyen,r.UserNhan,r.UserXuLy,r.DaChuyen,r.DaNhan,r.KhoXuLy,r.NgayChuyen,r.NgayNhan,r.CreatedDate FROM (SELECT C002301 ChuyenHangId,C002307 Ngay,C002319 CHName  FROM [192.168.1.98\CAMSOFT].[POSPRO_20130107].[dbo].[T0023] WHERE C002301 LIKE '%TH-%' AND C002304 < 0 AND c002307 >= '{0}' AND c002307 <= '{1}' ) AS l LEFT JOIN [Pharmacity_Project].[dbo].[ChuyenHang] AS r ON l.ChuyenHangId=r.ChuyenHangId WHERE l.ChuyenHangId LIKE N'%{2}%' AND CHName LIKE '%{3}%' ";
            DateTime dFrom = DateTime.Parse(dateFrom.Text);
            DateTime dTo = DateTime.Parse(dateTo.Text);
            string sql = string.Format(str, dFrom.ToString("yyyy-MM-dd 00:00:00.001"), dTo.ToString("yyyy-MM-dd 23:59:59.999"), txtMaChuyenHang.Text, ddlCuaHangChuyen.SelectedValue);
            if (ddlCuaHangNhan.SelectedIndex > 0)
                sql += " AND r.CuaHangNhan LIKE '%" + ddlCuaHangNhan.SelectedValue + "%' ";
            if (ddlTrangThai.SelectedValue != "")
                sql += " AND r.KhoXuLy=" + ddlTrangThai.SelectedValue;
            if (ddlDaNhan.SelectedValue != "")
                sql += " AND r.DaNhan=" + ddlDaNhan.SelectedValue;
            var ds = database.ExecuteQuery(sql);
            if (ds.Tables.Count > 0)
            {
                DataTable dtPerson = ds.Tables[0];
                DataView dvPerson = new DataView(dtPerson);

                dvPerson.Sort = ViewState["SortExpression"].ToString();
                GridView1.DataSource = dvPerson;
                GridView1.DataBind();
            }

        }

        protected void dateFrom_TextChanged(object sender, EventArgs e)
        {
            LoadGridview();
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            string[] strSortExpression = ViewState["SortExpression"].ToString().Split(' ');
            if (strSortExpression[0] == e.SortExpression)
            {
                if (strSortExpression[1] == "ASC")
                {
                    ViewState["SortExpression"] = e.SortExpression + " " + "DESC";
                }
                else
                {
                    ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
                }
            }
            else
                ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
            LoadGridview();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            LoadGridview();
        }

        protected void btnRefest_Click(object sender, EventArgs e)
        {
            LoadGridview();
        }

        protected void cbDaNhan_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            string s = @"UPDATE [ChuyenHang] SET [UserNhan] = '{0}' ,[DaNhan] = {1} ,[NgayNhan] = '{2}' WHERE ChuyenHangId='{3}'";
            string sql = "";
            if (cb.Checked)
            {
                sql = string.Format(s, UserInfo.UserID, cb.Checked ? 1 : 0, DateTime.Now, cb.ValidationGroup);
                database.ExecuteQuery(sql);
                GhiLog(cb.ValidationGroup, "Nhận hàng",
                   string.Format("[{0}][{1}] báo nhận hàng lúc {2}", UserInfo.Stores, UserInfo.UserName, DateTime.Now)
                   );
            }
            else
            {

                sql = string.Format(s, UserInfo.UserID, cb.Checked ? 1 : 0, DateTime.Now, cb.ValidationGroup);
                database.ExecuteQuery(sql);
                GhiLog(cb.ValidationGroup, "Sửa Nhận hàng",
                   string.Format("[{0}][{1}] sửa tình trạng nhận hàng thành chưa nhận hàng lúc {2}", UserInfo.Stores, UserInfo.UserName, DateTime.Now)
                   );
            }
            LoadGridview();


        }
        void GhiLog(string ChuyenHangId, string action = "", string detail = "")
        {
            string s = @"INSERT INTO [Pharmacity_Project].[dbo].[Log_ChuyenHang]
           ([ChuyenHangId]
           ,[UserId]
           ,[HanhDong]
           ,[Detail]
           ,[CreatedDate])
     VALUES
           ('{0}'
           ,'{1}'
           ,N'{2}'
           ,N'{3}'
           ,GETDATE())";

            string sql = string.Format(s, ChuyenHangId, UserInfo.UserID, action, detail);
            database.ExecuteQuery(sql);
        }

        public string NotifyText(string ChuyenHangId)
        {

            return "ChuyenHangId:" + ChuyenHangId;
        }

        public string ConvertUserIdToUserName(string userId)
        {
            if (listUser == null)
            {
                string sql = @"SELECT [C001900] UserId
                              ,[C001912] Name
                              ,[C001901] UserName
                              ,[C001905] FirstName
                              ,[C001904] LastName
                              ,[C001909] Store
                          FROM [192.168.1.98\CAMSOFT].[POSPRO_20130107].[dbo].[T0019]
                        WHERE [C001912] IS NOT NULL";
                var ds = database.ExecuteQuery(sql);
                if (ds.Tables.Count > 0)
                {
                    var dt = ds.Tables[0];
                    listUser = dt.AsEnumerable().Select(c => new ModelUser()
                    {
                        ModelUserId = c.Field<string>("UserId"),
                        Name = c.Field<string>("Name"),
                        FirstName = c.Field<string>("FirstName"),
                        LastName = c.Field<string>("LastName"),
                        Store = c.Field<string>("Store"),
                        UserName = c.Field<string>("UserName"),
                        
                    }).ToList();
                }
            }
            var model = listUser.FirstOrDefault(c=>c.ModelUserId==userId);
            if (model != null)
                return model.UserName;
            else
                return "###";
        }
     

    }
}